package net.ecpt.clm.rest;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.UtilValidate;

public class PayRaneUtil {

    /**
     * @param characterEncoding
     * @param param
     * @param key
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String createSign(Map<String, Object> param, String key) {
	// 签名步骤一：按字典排序参数
	List list = new ArrayList(param.keySet());
	Object[] ary = list.toArray();
	Arrays.sort(ary);
	list = Arrays.asList(ary);
	String str = "";
	for (int i = 0; i < list.size(); i++) {

	    if (UtilValidate.isNotEmpty(param.get(list.get(i) + ""))) {
		str += list.get(i) + "=" + param.get(list.get(i) + "") + "&";
	    }
	}
	// 签名步骤二：加上key
	str += "key=" + key;
	// 步骤三：加密并大写
	System.out.println(str);
	str = PayRaneUtil.MD5Encode(str, "utf-8").toUpperCase();
	return str;
    }

    public static String MD5Encode(String origin, String charsetName) {
	String resultString = null;
	try {
	    resultString = new String(origin);
	    MessageDigest md = MessageDigest.getInstance("MD5");
	    if (UtilValidate.isEmpty(charsetName)) {
		resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
	    } else {
		resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));
	    }
	} catch (Exception e) {

	}
	return resultString;
    }

    public static String byteArrayToHexString(byte b[]) {
	StringBuffer resultSb = new StringBuffer();
	for (int i = 0; i < b.length; i++) {
	    resultSb.append(PayRaneUtil.byteToHexString(b[i]));
	}
	return resultSb.toString();
    }

    public static String byteToHexString(byte b) {
	int n = b;
	if (n < 0) {
	    n += 256;
	}
	int d1 = n / 16;
	int d2 = n % 16;
	return PayRaneUtil.hexDigits[d1] + PayRaneUtil.hexDigits[d2];
    }

    public static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
	    "e", "f" };

}
